package com.wonderland.butterfly.autoupdate.patch;

import com.wonderland.butterfly.autoupdate.model.GitSetting;
import com.wonderland.butterfly.autoupdate.model.Patch;
import com.wonderland.butterfly.jgit.GitUtil;
import com.wonderland.butterfly.util.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.shared.invoker.*;
import org.eclipse.jgit.api.errors.GitAPIException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Created by gaoxinyu on 2015-07-21 0021.
 */
public class AutoPatch {

    public void generatePatch(String propertiesPath) throws IOException, GitAPIException, MavenInvocationException {
        Properties prop = getProperties(propertiesPath);
        Patch patch = new Patch(prop);
        GitUtil.checkout(new GitSetting(prop), patch.getTargetVersion());
        generateSql(patch);
        generateWar(patch);
    }

    private void generateWar(Patch patch) throws MavenInvocationException, IOException {
        InvocationRequest request = new DefaultInvocationRequest();
        request.setPomFile(new File(patch.getPomFilePath()));
        List<String> list = new ArrayList<>();
        list.add("clean");
        list.add("package");
        if (StringUtils.isNotEmpty(patch.getProfile())) {
            list.add("-P" + patch.getProfile());
        }
        list.add("-Dmaven.test.skip=true");
        request.setGoals(list);
        Invoker invoker = new DefaultInvoker();
        invoker.execute(request);
        FileUtil.copyFile(patch.getGeneratedWarPath(), patch.getPatchWarPath());
    }

    private void generateSql(Patch patch) throws IOException {
        DatabasePatch databasePatch = new DatabasePatch(patch.getDatabasePatchDir(), patch.getPatchDir());
        databasePatch.generatePatch(patch.getPatchName(), patch.getOriginalVersion(), patch.getTargetVersion());

    }

    private Properties getProperties(String propPath) throws IOException {
        Properties property = new Properties();
        FileInputStream fis = new FileInputStream(propPath);
        property.load(fis);
        fis.close();
        return property;
    }

    public static void main(String[] args) throws GitAPIException, IOException, MavenInvocationException {
        AutoPatch autoPatch = new AutoPatch();
//        autoPatch.generatePatch("D:\\workspace\\butterfly\\butterfly\\application.properties");
        autoPatch.generatePatch(args[0]);
    }
}
